﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Net;
using System.IO;
namespace siguo_shrx.server
{
    public class Server
    {
        public void UploadFileByFtp(string url, string username, string password, string localFileName, string remoteFileName)
        {
            try
            {
                FtpWebRequest fwr = (FtpWebRequest)FtpWebRequest.Create(url + remoteFileName);
                fwr.Method = WebRequestMethods.Ftp.UploadFile;
                fwr.Credentials = new NetworkCredential(username, password);
                fwr.UsePassive = true;
                fwr.UseBinary = true;
                fwr.KeepAlive = false;
                Stream stream = fwr.GetRequestStream();
                byte[] buffer = File.ReadAllBytes(localFileName);
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();
            }
            catch (Exception)
            {
                throw new Exception("更新IP信息出错！");
            }
        }

        public string GetIP()//获得外网IP
        {
            Uri uri = new Uri("http://ipseeker.cn/index.php");
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = 0;
            req.CookieContainer = new System.Net.CookieContainer();
            req.GetRequestStream().Write(new byte[0], 0, 0);
            HttpWebResponse res = (HttpWebResponse)(req.GetResponse());
            StreamReader rs = new StreamReader(res.GetResponseStream(), System.Text.Encoding.GetEncoding("GB2312"));
            try
            {
                string s = rs.ReadToEnd();
                //this.textBox.Text = s;

                rs.Close();
                req.Abort();
                res.Close();
                System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, @"查询结果： (?<IP>[0-9.]*)");
                if (m.Success)
                {
                    return m.Groups["IP"].Value;
                }
                else
                {
                    return "失败！";
                }
            }
            catch (Exception )
            {

                return "失败！";
            }
        }
    }
}
